package pl.edu.agh.winmon.analise;

import java.util.Collection;
import java.util.Date;

import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;

import pl.edu.agh.winmon.hibernate.ProcessStatEntry;
import pl.edu.agh.winmon.hibernate.Session;

public class ProccessPropSeriesProvider implements ProcessSeriesProvider {

	public static final String CPU_USAGE = "CPU usage";

	public static final String MEMORY_USAGE = "Total memory usage";

	public static final String VIRTUAL_USAGE = "Virtual memory usage";

	public static final String FILE_DESCRIPTORS = "File descriptors";

	public static final String THREADS = "Active threads";

	public TimeSeriesCollection provideSeries(Session session,
			Collection<pl.edu.agh.winmon.hibernate.Process> processes,
			long start, long end, String prop) {

		TimeSeriesCollection collection = new TimeSeriesCollection();

		for (pl.edu.agh.winmon.hibernate.Process process : processes) {

			TimeSeries timeSeries = new TimeSeries(process.getPid());

			if (process != null) {
				for (ProcessStatEntry entry : process.getStatEntries()) {
					if (entry != null) {
						if (entry.getTurn().getStartTime() >= start
								&& entry.getTurn().getStartTime() < end) {

							if (CPU_USAGE.equals(prop)) {
								timeSeries.addOrUpdate(new Second(new Date(
										entry.getTurn().getStartTime())), entry
										.getCpuUsage() * 100.0);
							} else if (MEMORY_USAGE.equals(prop)) {
								timeSeries.addOrUpdate(new Second(new Date(
										entry.getTurn().getStartTime())), entry
										.getTotalResidentMemory());
							} else if (VIRTUAL_USAGE.equals(prop)) {
								timeSeries.addOrUpdate(new Second(new Date(
										entry.getTurn().getStartTime())), entry
										.getTotalVirtualMemory());
							} else if (FILE_DESCRIPTORS.equals(prop)) {
								timeSeries.addOrUpdate(new Second(new Date(
										entry.getTurn().getStartTime())), entry
										.getFileDescriptors());
							} else if (THREADS.equals(prop)) {
								timeSeries.addOrUpdate(new Second(new Date(
										entry.getTurn().getStartTime())), entry
										.getActiveThreads());
							}

						}
					}
				}
			}

			collection.addSeries(timeSeries);

		}

		return collection;
	}
}
